package classesBD;

import aplicacao.funcoes;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Pessoal
 */
public class Journal extends MeioPublicacao{
  private int idJournal;
  private String numero;

  public int getIdJournal() {
    return idJournal;
  }
  
  
  @Override
  public int insere(boolean checaExistencia){
    if (checaExistencia){
      idJournal = existe(super.nome);
    }
    if (idJournal == 0){
        try {
            String[] campos = new String[3]; 
            campos[0] = "default";
            campos[1] = numero;
            campos[2] = Integer.toString(super.insere(false));
            String query = funcoes.montaInsert("JOURNAL", campos);
            idJournal =  Conexao.executa(query, true);
            Conexao.fecha();
        } catch (SQLException ex) {
            Logger.getLogger(Journal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return idJournal;  
  }

  @Override
  public void buscaPorId(int id) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  }

  @Override
  public void buscaPorNome(String nome) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  }

  @Override
  public boolean preencheAttr(String attr, String valor) {
    String atributo = attr.toLowerCase();
    boolean result = true;
    switch(atributo){
      case "number":numero = valor;
        break;
      default: result = super.preencheAttr(attr, valor);
    } 
    return result;
  }
  
  @Override
  public String existe(int id) {
    String query = "SELECT MP.NOME FROM JOURNAL J JOIN MEIOPUBLICACAO MP WHERE IDJOURNAL=" + Integer.toString(id);
    String[][] retorno = Conexao.pesquisa(query, 1);
    if (retorno.length > 0){
      return retorno[0][0];
    }else{
      return "";
    }
  }

  @Override
  public int existe(String nome) {
    nome = nome.toLowerCase();
    String query = "SELECT J.IDJOURNAL FROM JOURNAL J JOIN MEIOPUBLICACAO MP ON J.IDMEIOP = MP.IDMEIOP AND LOWER(MP.NOME)=" + funcoes.quotedStr(nome);
    String[][] retorno = Conexao.pesquisa(query, 1);
    if (retorno.length > 0){
      return Integer.parseInt(retorno[0][0]);
    }else{
      return 0;
    }
  }
}
